import { HsAdminTablePage } from '@hs-admin/base-components'

import { EchartsModule } from '@hs-server/components'

import { useNewPage } from '@hs-admin/utils'

import * as Diff from 'diff'
import {
  postCompanyInfoDetailQueryChangeDetails,
  getCompanyInfoDetailQueryOverviewOfChanges,
  getCompanyInfoDetailQueryChangeBarChart
} from '@/api/companyDetail/BasicInfor'

import { useEffect, useState } from 'react'

import { Typography } from 'antd'

import * as echarts from 'echarts/core'

import React from 'react'

const echartsRef: any = React.createRef()

const ChangeLog = (props: any) => {
  const { companyCode, hiddenModule } = props
  const { pagination } = useNewPage(getData)

  const [listData, setListData] = useState([])

  const [pieData, setPieData] = useState([])

  const [expanded, setExpanded] = useState(false)

  const [DataMap, setDataMap]: any = useState({})

  const [xAxisData, setXAxisData] = useState([])

  const [lineData, setlineData] = useState([])

  const rows = 3

  const changeTextContent = (row: any) => {
    const diff = Diff.diffChars(row.changeBefore || '', row.changeAfter || '')
    let content = ''
    diff.forEach((part: any) => {
      if (part.added) {
        content = row.changeAfter.replace(part.value, `<span style='color:#f00'>${part.value}</span>`)
      }
    })
    return <span dangerouslySetInnerHTML={{ __html: content }} />
  }

  const columns: any[] = [
    {
      title: '变更日期',
      dataIndex: 'changeDate'
    },
    {
      title: '变更项目',
      dataIndex: 'changeTypeStd'
    },
    {
      title: '变更前',
      dataIndex: 'changeBefore'
    },
    {
      title: '变更后',
      dataIndex: 'content',
      render: (_value: string, row: any, _index: number) => changeTextContent(row)
    }
  ]

  async function getData() {
    const res = await postCompanyInfoDetailQueryChangeDetails({
      pageNo: pagination.current,
      current: pagination.current,
      pageSize: pagination.pageSize,
      companyCode: companyCode
    })
    if (res.code === 200 && res?.data) {
      if (res.data.list) {
        const arr = (res.data.list || res.data.records).map((item: any, index: any) => {
          item._index = index + (Number(res.data['current'] || pagination.page) - 1) * Number(res.data['pageSize'] || pagination.pageSize) + 1
          return item
        })
        setListData(arr)
      } else {
        setListData([])
      }

      pagination.total = res.data.total
    }
    return res.data
  }

  // 获取概括，饼图加文字内容
  const getEllipsisContent = async () => {
    const res = await getCompanyInfoDetailQueryOverviewOfChanges({ companyCode: companyCode })
    if (res.code === 200) {
      const data: any = Object.keys(res?.data)
        .map((item) => ({ name: item, value: res.data[item], unit: '条' }))
        .sort((a, b) => b.value - a.value)
      setPieData(data)
      hiddenModule(data)
      // 构建一个map
      data?.forEach((item: any) => {
        setDataMap((prev: any) => {
          return { ...prev, [item.name]: item }
        })
        // DataMap[(item as Record<string, string>).name] = item
      })
    }
  }

  const Options = {
    tooltip: {
      trigger: 'item',
      formatter(params: any) {
        const { name, value, unit } = params.data
        return `变更概况 <br/>${name}:${value}${unit}`
      }
    },

    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 'center',
      // bottom: 20,
      selectedMode: false,
      icon: 'path://M0 0 H8 V16 H0 Z',
      formatter(name: any) {
        const arr = [`{nameStyle|${name}}`, `{valueStyle|${DataMap[name]?.value}}条`]
        return arr.join('')
      },
      textStyle: {
        rich: {
          nameStyle: {
            width: 200
          },
          valueStyle: {
            width: 30
          }
        }
      }
    }
  }

  const series = [
    {
      name: '变更概况',
      type: 'pie',
      radius: ['50%', '70%'],
      center: ['25%', '50%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 5
      },
      label: {
        show: false,
        position: 'center',
        formatter(params: { name: any; value: any }) {
          if (params.name) {
            return `{value|${params.value}条}\n{name|${params.name}}`
          }
          return ''
        },
        rich: {
          name: {
            color: '#333333',
            fontSize: 14,
            lineHeight: 20,
            align: 'center'
          },
          value: {
            color: '#333333',
            fontSize: 28,
            lineHeight: 38,
            align: 'center',
            fontWeight: 700,
            padding: [0, 5, 0, 0]
          }
        }
      },
      emphasis: {
        label: {
          show: true
        },
        scaleSize: 3,
        scale: true
      },

      labelLine: {
        show: false
      },
      data: pieData
    }
  ]

  const lineOptions = {
    xAxis: {
      type: 'category',
      data: xAxisData,
      axisLine: {
        lineStyle: {
          color: '#eee' // 设置 x 轴颜色
        }
      },
      axisLabel: {
        color: '#B3B3B3'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter(params: any) {
        const { dataIndex, name } = params

        return `${name}年 <br/>变更次数：${lineData[dataIndex]}${'条'}`
      },
      className: 'tooltip-light'
    },
    yAxis: {
      type: 'value',
      splitLine: {
        show: true, // 显示分隔线
        lineStyle: {
          type: 'dashed', // 设置分隔线为虚线
          color: '#eee', // 设置分隔线颜色
          width: 1 // 设置分隔线宽度
        }
      },
      axisLine: {
        lineStyle: {
          color: '#eee' // 设置 y 轴颜色
        }
      },
      axisLabel: {
        color: '#B3B3B3'
      }
    }
  }

  const lineSeries = [
    {
      data: lineData,
      type: 'bar',
      barWidth: '12',
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#1492FF' },
          { offset: 1, color: '#3CC7FF' }
        ]),
        borderRadius: [6, 6, 0, 0]
      }
    }
  ]

  const getLineChart = async () => {
    const res = await getCompanyInfoDetailQueryChangeBarChart({ companyCode })
    if (res.code === 200) {
      const xAxis: any = Array.from(Object.keys(res.data))
      const data = xAxis.map((key: any) => res.data[key])

      setXAxisData(xAxis)

      setlineData(data)
    }
  }

  useEffect(() => {
    getEllipsisContent()
    getLineChart()
  }, [])

  return (
    <div id="变更信息" className="change-log">
      <div className="change-log-overfiew-content">
        <div className="change-sub-title">变更概况</div>
        <div className="overfiew-content">
          <Typography.Paragraph
            ellipsis={{
              rows,
              expandable: 'collapsible',
              expanded,
              onExpand: (_, _info) => setExpanded((c) => !c)
            }}>
            {pieData.map((item: any, index) => (
              <span key={index}>
                {item.name}
                <span style={{ color: '#fe5332' }}>{item.value} </span> 条 {index === pieData?.length - 1 ? '。' : '，'}
              </span>
            ))}
          </Typography.Paragraph>
        </div>
        <div className="overfiew-chart">
          <div className="chart-item">
            <EchartsModule autoPlay={true} onRef={echartsRef} seriesData={series} options={Options}></EchartsModule>
          </div>
          <div className="chart-item">
            <EchartsModule onRef={echartsRef} seriesData={lineSeries} options={lineOptions}></EchartsModule>
          </div>
        </div>
      </div>
      <div className="change-log-overfiew-content">
        <div className="change-sub-title pb-20px">变更详情</div>
        <div>
          <HsAdminTablePage
            scroll={{ x: 800, y: 650 }}
            columns={columns}
            dataSource={listData}
            id="intellectual-property-patent"
            pagination={pagination}
            size="small"
            rowKey={(record: any) => `${record.changeDate}${record.changeTypeStd}`}
          />
        </div>
      </div>
    </div>
  )
}
export default ChangeLog
